//
//  UIView+Marker.m
//  KoalaPad
//
//  Created by 张英堂 on 15/4/8.
//  Copyright (c) 2015年 zyt. All rights reserved.
//

#import "UIView+Marker.h"
#import <objc/runtime.h>


#define KMARKANIMTAIONKEY @"markanimation"

@implementation UIView (Marker)

static char lineShapeKey;

- (void)starMarker{
    
    CAShapeLayer *lineShape = objc_getAssociatedObject(self, &lineShapeKey);
    
    if (lineShape == nil) {
        
        CGMutablePathRef linepath = nil;
        
        linepath = CGPathCreateMutable();
        lineShape = [CAShapeLayer layer];
        
        lineShape.lineWidth = 4.0;
        lineShape.lineCap = kCALineCapRound;
        lineShape.strokeColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor;
        
        CGPathMoveToPoint(linepath, NULL, 1, self.frame.size.height*0.2);
        CGPathAddLineToPoint(linepath, NULL, 1, self.frame.size.height - self.frame.size.height*0.2);
        
        lineShape.path = linepath;
        
        objc_setAssociatedObject(self, &lineShapeKey, lineShape, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        
        CGPathRelease(linepath);
    }
    
    if (lineShape.superlayer != self.layer) {
        [self.layer addSublayer:lineShape];
    }
    
    if ([lineShape animationKeys].count >= 1) {
        return;
    }
    
    [lineShape addAnimation:[self markerTransaction] forKey:KMARKANIMTAIONKEY];
}

- (void)setMarkerOffsetY:(CGFloat)offsetY{
    CAShapeLayer *lineShape = objc_getAssociatedObject(self, &lineShapeKey);
    if (lineShape == nil) {
        [self starMarker];
        return;
    }
    
    CATransform3D tran = CATransform3DMakeTranslation(0, offsetY, 0);
    lineShape.transform = tran;
}

-(void)setMarkerOffsetX:(CGFloat)offsetX{
    
    NSLog(@"%f -----", offsetX);

    CAShapeLayer *lineShape = objc_getAssociatedObject(self, &lineShapeKey);
    if (lineShape == nil) {
        return;
    }
    
    NSLog(@"%f -----", offsetX);

    CATransform3D tran = CATransform3DMakeTranslation(offsetX, 0, 0);
    
    lineShape.transform = tran;
}

- (void)stopMarker{
    CAShapeLayer *lineShape = objc_getAssociatedObject(self, &lineShapeKey);
    if (lineShape) {
        [lineShape removeAllAnimations];
        
        if (lineShape.superlayer == self.layer) {
            [lineShape removeFromSuperlayer];
        }
    }
}

- (CAAnimation *)markerTransaction{
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    
    animation.autoreverses = YES;
    animation.duration = 0.4;
    animation.repeatCount = 999;
    animation.removedOnCompletion = YES;
    
    animation.fillMode = kCAFillModeForwards;
    animation.fromValue        =   [NSNumber numberWithFloat:1];
    animation.toValue          =   [NSNumber numberWithFloat:0.1];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    return animation;
}

@end
